<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.input.type" style="width: 130px">
            <el-option label="退款单号" value="refund_no"></el-option>
            <el-option label="采购单号" value="purchase_no"></el-option>
            <el-option label="SKU" value="sku"></el-option>
            <el-option label="采购单号/SKU" value="purchase_no_sku"></el-option>
          </el-select>
          <VBatchInput v-model="form.input.value" @search="query" class="w-60" />
        </VGroup>
        <VSelect v-model="form.refund_status" placeholder="退款状态" :options="options.refund_status || []" multiple
          collapse-tags style="min-width: 160px" />
        <!-- <VSelect v-model="form.settlement_type" placeholder="结算方式" :options="options.settlement_type || []" multiple
          collapse-tags style="min-width: 160px" /> -->
        <VSelect v-model="form.supplier_name" placeholder="供应商" type="supplierName" allow-create style="min-width: 200px" multiple
          collapse-tags clearable filterable />
        <VSelect v-model="form.purchase_status" placeholder="采购单状态" :options="options.purchase_status || []" multiple
          collapse-tags style="min-width: 160px" />
        <VCascader v-model="form.create_user_id" placeholder="申请人" multiple collapse-tags style="min-width: 160px" />
        <VCascader v-model="form.audit_user_id" placeholder="审核人" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.source_type" placeholder="来源类型" :options="options.source_type" multiple collapse-tags style="min-width: 180px" />
        <VSelect v-model="form.refund_type" placeholder="退款类型" :options="options.refund_type" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.refund_account" placeholder="退款账号" :options="options.payment_account" multiple collapse-tags style="min-width: 220px" />
        <VSelect v-model="form.refund_transaction_status" placeholder="1688退款状态" :options="options.refund_transaction_status" multiple collapse-tags style="min-width: 160px" />
        <el-input v-model="form.platform_refund_no" placeholder="1688退款单号" class="w-60" />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 100px">
            <el-option label="申请时间" value="create_time"></el-option>
            <el-option label="审核时间" value="audit_time"></el-option>
            <el-option label="退款到账时间" value="refund_received_time"></el-option>
          </el-select>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VAudit auth="/purchase/finance/refund/audit" field="r_id" url="/v1/finance/refund/batch-audit"
          :tableRef="tableRef" @success="query" />
        <VButton auth="/purchase/finance/refund/financeConfirm" type="primary" @click="handleBatch('confirm', row)">
          财务确认</VButton>
        <VButton auth="/purchase/finance/refund/submit" @click="handleBatch('submit', row)">提交</VButton>
        <VButton auth="/purchase/finance/refund/revoke" @click="handleBatch('revoke', row)">撤回</VButton>
        <VExport auth="/purchase/finance/refund/export" mainKey="r_id" :name="baseName" :tableRef="tableRef" task
          class="ml-auto" />
      </template>
    </VTable>
    <Edit ref="editRef" :options="options" @success="query" />
    <VLog ref="logRef" />
    <Confirm ref="confirmRef" :options="options" @success="query" />
    <ViewImage ref="viewImageRef" />
  </VPage>
</template>
  
<script setup lang="jsx" name="Account">
import api from './api'
import Confirm from './components/Confirm'
import Edit from './components/Edit'
import { getOption } from '@/api/public'
import { ElMessage, ElMessageBox } from 'element-plus'
import { resMessage } from '@/utils/res'

const baseName = 'refund'
const tableRef = ref()
const logRef = ref()
const viewImageRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: 'payment' }).then(res => res.data),
  getOption({ type: 'purchase' }).then(res => res.data),
  getOption({ type: baseName }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})


// 批量操作
const auditRef = ref()
const batchPrintRef = ref()
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const r_ids = selection.map(d => d.r_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    confirm: () => {
      confirmRef?.value.open(r_ids)
    },
    submit: () => {
      showLoading()
      api.submit({ r_ids }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(closeLoading)
    },
    revoke: () => {
      showLoading()
      api.revoke({ r_ids }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(closeLoading)
    },
  }
  handle[name]()
}

// 单行操作
const confirmRef = ref()
const editRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { r_id } = row
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    look: () => {
      editRef?.value.open(r_id, { look: true })
    },
    edit: () => {
      editRef?.value.open(r_id)
    },
    confirm: () => {
      confirmRef?.value.open([r_id])
    },
    submit: () => {
      showLoading()
      api.submit({ r_ids: [r_id] }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(closeLoading)
    },
    revoke: () => {
      showLoading()
      api.revoke({ r_ids: [r_id] }).then(res => {
        resMessage({
          res,
          success: () => {
            ElMessage.success('操作成功')
            query()
          }
        })
      }).finally(closeLoading)
    },
    audit: () => {
      auditRef?.value.open([row], { label: '审核', value: 1 })
    },
    cancel: () => {
      ElMessageBox.confirm('是否确认作废？', '取消', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          api.cancel({ r_id }).then(res => {
            ElMessage.success('操作成功')
            query()
          }).finally(closeLoading)
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    log: () => {
      logRef?.value.open({ log_type: baseName, r_id })
    },
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  rowConfig: { height: 72 },
  showHeaderOverflow: false,
  formConfig: {
    data: {
      input: { type: 'refund_no', value: '' },
      dateRange: { type: 'create_time', value: [], range: true },
    }
  },
  columns: [
    { type: 'checkbox', width: 40, fixed: 'left' },
    {
      minWidth: 150, slots: {
        header: () => <div>退款单号<br />仓库</div>,
        default: ({ row }) => <div>
          <VText value={row.refund_no} type='link' onClick={() => handleRow('look', row)} />
          <VText title='仓库' value={row.destination_warehouse_name}></VText>
        </div>
      }
    },
      {
        minWidth: 140, slots: {
          header: () => <div>采购单号</div>,
          default: ({ row }) => <VText value={row.purchase_no} />
        }
      },
    {
      minWidth: 100, slots: {
        header: () => <div>退款状态</div>,
        default: ({ row }) => <VText value={row.refund_status_name} />
      }
    },
    {
      minWidth: 200, slots: {
        header: () => <div>1688退款单号<br/>1688退款状态</div>,
        default: ({ row }) => <div>
          <VText value={row.platform_refund_no} />
          <VText value={row.refund_transaction_status_name} />
        </div>
      }
    },
    {
      minWidth: 220, slots: {
        header: () => <div>供应商<br />结算方式/供应商类型</div>,
        default: ({ row }) => <div>
          <VText value={row.supplier_name} line={1} />
          <VText title='结算方式' value={row.period_name} line={1}></VText>
          <VText title='供应商类型' value={row.purchase_type_name}></VText>
        </div>
      }
    },
    {
      minWidth: 150, slots: {
        header: () => <div>来源类型<br />来源单号</div>,
        default: ({ row }) => <div>
          <div>{row.source_type_name}</div>
          <div>{row.source_no}</div>
        </div>
      }
    },
    {
      minWidth: 140, slots: {
        header: () => <div>退款sku</div>,
        default: ({ row, rowIndex }) => <VMore key={rowIndex}>
            {{
              default: (line) => (row.sku || []).map(d => <div class='w-full'>
                <VText value={d} line={line} />
              </div>)
            }}
          </VMore>
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>退款类型</div>,
        default: ({ row }) => row.refund_type_name
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>下单金额</div>,
        default: ({ row }) => row.is_drawback === 1 ? row.total_purchase_price : row.total_purchase_price_tax
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>已付金额</div>,
        default: ({ row }) => row.payment_price
      }
    },
    {
      minWidth: 100, slots: {
        header: () => <div>已退款金额</div>,
        default: ({ row }) => row.refund_price
      }
    },
    {
      minWidth: 110, slots: {
        header: () => <div>申请退款金额</div>,
        default: ({ row }) => row.apply_price
      }
    },
    {
      minWidth: 110, slots: {
        header: () => <div>申请退款运费</div>,
        default: ({ row }) => <VText value={row.apply_tracking_price} />
      }
    },
    {
      minWidth: 120, slots: {
        header: () => <div>退款交易号</div>,
        default: ({ row }) => <VText value={row.refund_transaction_no} />
      }
    },
    {
      minWidth: 120, slots: {
        header: () => <div>退款备注</div>,
        default: ({ row }) => <VText value={row.remark} line={3} />
      }
    },
    {
      minWidth: 150, slots: {
        header: () => <div>退款凭证</div>,
        default: ({ row, rowIndex }) => <VMore key={rowIndex}>
          {{
            default: (line) => (row.refund_voucher || []).map(d => <div class='w-full'>
              <VText value={d} type='link' line={line} onClick={() => viewImageRef?.value.open(d)} />
            </div>)
          }}
        </VMore>
      }
    },
    {
      minWidth: 210, slots: {
        header: () => <div>退款信息</div>,
        default: ({ row }) => <div>
          <VText title='收款账号' value={row.refund_account} title-position='top'/>
          <VText title='退款到账时间' value={row.refund_received_time}/>
        </div>
      }
    },
    {
      minWidth: 160, slots: {
        header: () => <div>审核备注</div>,
        default: ({ row }) => <div>
          <VText title='审核备注' value={row.audit_remark} line={2} />
          <VText title='财务确认' value={row.confirm_remark} line={2} />
        </div>
      }
    },
    {
      minWidth: 160, slots: {
        header: () => <div>申请人<br />申请时间</div>,
        default: ({ row }) => <div>
          <VText value={row.create_user} />
          <VText value={row.create_time} />
        </div>
      }
    },
    {
      minWidth: 160, slots: {
        header: () => <div>审核人<br />审核时间</div>,
        default: ({ row }) => <div>
          <VText value={row.audit_user} />
          <VText value={row.audit_time} />
        </div>
      }
    },
    {
      title: '操作', width: 120, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          const { refund_status } = row
          // refund_status	退款状态1待提交2待审核3待财务确认4已完结5已驳回6已作废
          return [<div class='nm flex flex-wrap gap-x-2 gap-y-1'>
            <VButton auth="/purchase/finance/refund/detail" link type="primary" onClick={() => handleRow('look', row)}>查看</VButton>
            {[1, 5].includes(refund_status) ? <VButton auth="/purchase/finance/refund/edit" link type="primary" onClick={() => handleRow('edit', row)}>编辑</VButton> : ''}
            {[1, 5].includes(refund_status) ? <VButton auth="/purchase/finance/refund/submit" link type="primary" onClick={() => handleRow('submit', row)}>提交</VButton> : ''}
            {[2].includes(refund_status) ? <VButton auth="/purchase/finance/refund/revoke" link type="primary" onClick={() => handleRow('revoke', row)}>撤回</VButton> : ''}
            {/* {[2].includes(refund_status) ? <el-button link type="primary" onClick={() => handleRow('audit', row)}>审核</el-button> : ''} */}
            {[3].includes(refund_status) ? <VButton auth="/purchase/finance/refund/financeConfirm" link type="primary" onClick={() => handleRow('confirm', row)}>财务确认</VButton> : ''}
            {[1,5].includes(refund_status) ? <VButton auth="/purchase/finance/refund/cancel" link type="primary" onClick={() => handleRow('cancel', row)}>作废</VButton> : ''}
            {row.refund_voucher[0] ? <VButton link type="primary" onClick={() => viewImageRef?.value.open(row.refund_voucher[0])}>预览</VButton> : ''}
            <VButton auth="/purchase/finance/refund/log" link type="primary" onClick={() => handleRow('log', row)}>日志</VButton>
          </div>]
        }
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page })
    }
  }
})
</script>
  